/**
 * 用户相关状态管理
 * 使用 Pinia 管理用户登录状态、权限等
 */
import { defineStore } from 'pinia'
import { login, getUserInfo, logout } from '@/api/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  // 状态
  state: () => ({
    token: localStorage.getItem('token') || '',
    userId: '',
    username: '',
    realName: '',
    avatar: '',
    roles: []
  }),
  
  // 计算属性
  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    // 用户是否有指定角色
    hasRole: (state) => (role) => state.roles.includes(role),
  },
  
  // 方法
  actions: {
    /**
     * 用户登录
     * @param {Object} userInfo - 登录信息
     */
    async loginAction(userInfo) {
      try {
        const data = await login(userInfo)
        this.token = data.token
        localStorage.setItem('token', data.token)
        return data
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },
    
    /**
     * 获取用户信息
     */
    async getUserInfoAction() {
      try {
        const data = await getUserInfo()
        this.userId = data.userId
        this.username = data.username
        this.realName = data.realName
        this.avatar = data.avatar || ''
        this.roles = data.roles || []
        return data
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },
    
    /**
     * 用户登出
     */
    async logoutAction() {
      try {
        await logout()
        this.resetState()
        // 重定向到登录页
        router.push('/login')
      } catch (error) {
        console.error('登出失败:', error)
      }
    },
    
    /**
     * 重置状态
     */
    resetState() {
      this.token = ''
      this.userId = ''
      this.username = ''
      this.realName = ''
      this.avatar = ''
      this.roles = []
      localStorage.removeItem('token')
    }
  }
}) 